package s03;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName BSServer
 * @Description TODO
 * @Author Li
 * @Date 2022/9/9 2:20
 * @ModifyDate 2022/9/9 2:20
 * @Version 1.0
 */
public class BSServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);

        while (true) {
            Socket socket = server.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 转换流，读取浏览器请求的第一行数据
                        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String line = br.readLine();
                        // 获取请求资源的路径
                        String[] arr = line.split(" ");
                        String path = arr[1].substring(1);

                        // 读取客户端请求的资源文件
                        System.out.println(path);
                        FileInputStream fis = new FileInputStream(path);
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        // 字节输出流，将文件回写客户端
                        OutputStream os = socket.getOutputStream();
                        // 写入HTTP协议响应头，固定写法
                        os.write("HTTP/1.1 200 OK\r\n".getBytes());
                        os.write("Content-Type:text/html\r\n".getBytes());
                        // 必须要写入空行，否则浏览器不会解析，解析了也会乱码
                        os.write("\r\n".getBytes());
                        while ((len = fis.read(bytes)) != -1) {
                            os.write(bytes, 0, len);
                        }
                        // 关闭资源
                        os.close();
                        fis.close();
                        br.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
